﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.Reflection;
using FCNS.Data.Table;

namespace DoubleH.Utility.Search
{
    public class SearchUtility
    {
        /// <summary>
        /// 在指定的源集合中搜索元素
        /// </summary>
        /// <param name="source">源集合</param>
        /// <param name="searchField">要搜索的类中的属性名称</param>
        /// <param name="searchText">要搜索的文本</param>
        /// <returns></returns>
        public IList Search(IList source, string searchText,params string[] searchField)
        {
            if (source == null)
                return null;

            if (searchField == null || searchField.Length == 0)
                return source;
            
            List<object> temp = new List<object>();
            foreach (object obj in source)
                if (Equals(obj, searchText, searchField))
                    temp.Add(obj);

            return temp;
        }

        private bool Equals(object source, string searchText, params string[] searchField)
        {
            Type t = source.GetType();
            PropertyInfo[] properties = t.GetProperties();
            Object p = t.InvokeMember("", System.Reflection.BindingFlags.CreateInstance, null, source, null);
            foreach (PropertyInfo pi in properties)
            {
                if (!searchField.Contains(pi.Name))
                    continue;

                if (pi.GetValue(source, null).ToString().ToUpper().Contains(searchText.ToUpper()))
                    return true;
            }
            return false;
        }

    }
}